package com.cyz.springdemo.util;

import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @program: springdemo
 * @description: 饿百签名工具类
 * @author: wangjie
 * @create: 2019-09-29 13:52
 **/
public class ErBaiSignUtil {

    /**
     * 根据参数获取签名
     * @return String
     */
    public static String getSign(Map<String, Object> data) throws UnsupportedEncodingException {
        TreeMap<String, Object> arr = new TreeMap<String, Object>();
        Gson gson = new Gson();
        arr.put("body", gson.toJson(data.get("body")));
        arr.put("cmd", data.get("cmd"));
        arr.put("encrypt", "");
        arr.put("secret", data.get("secret"));
        arr.put("source", data.get("source"));
        arr.put("ticket", data.get("ticket"));
        arr.put("timestamp", data.get("timestamp"));
        arr.put("version", data.get("version"));
        StringBuilder strSignTmp = new StringBuilder("");
        Iterator it = arr.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            strSignTmp.append(key + "=" + arr.get(key) + "&");
        }
        String strSign = strSignTmp.toString().substring(0, strSignTmp.length() - 1);
        //String sign = getMD5(strSign.toString());
        String sign = getMd5(strSign.toString());
        return sign;
    }

    public static String getMd5(String strSign) throws UnsupportedEncodingException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String str = byte2hex(md.digest(strSign.getBytes("utf-8")));
        return str.toUpperCase();
    }

    private static String byte2hex(byte[] b) {
        StringBuffer buf = new StringBuffer();

        for(int offset = 0; offset < b.length; ++offset) {
            int i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }

        return buf.toString();
    }


    /**
     * 获取MD5
     * @return String
     */
    /*public static String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }*/

    /**
     * 中文转unicode,如果参数中有中文，需要转一下
     *
     * @param gbString
     * @return
     */
    public static String gbEncoding(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    /**
     * 获取Ticket：时间戳+5个随机字母  ---》 MD5加密  ---》转换成大写字母  ---》再在左起第8、12、16、20位字符后面添加减号：
     * @return
     */
    public static String getTicket(String timestamp) throws UnsupportedEncodingException {

        String randomStr  = "";
        for (int i = 0; i<5; i++){
            char c = (char) (Math.random() * 26 + 'a');
            randomStr = randomStr + String.valueOf(c);
        }

        String baseTicket = timestamp + randomStr;
        String md5Ticket = getMd5(baseTicket);
        StringBuffer sb = new StringBuffer(md5Ticket);
        sb.insert(8,"-").insert(13,"-").insert(18,"-").insert(23,"-");
        return sb.toString();
    }


}
